package com.authine.cloudpivot.engine;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class EngineServiceApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(EngineServiceApplication.class);

        app.addInitializers(new ApplicationContextInitializer<ConfigurableApplicationContext>() {
            @Override
            public void initialize(ConfigurableApplicationContext applicationContext) {
                ConfigurableEnvironment env = applicationContext.getEnvironment();
                String driverClass = env.getProperty("spring.datasource.driver-class-name");

                if("com.mysql.jdbc.Driver".equals(driverClass)) {
                    String url = env.getProperty("spring.datasource.url").toLowerCase();

                    //jdbc:mysql://172.18.14.204:3306/cloudpivot?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&useSSL=false
                    //List<String> lists = Splitter.on("?").splitToList(url);
                    //String param = lists.get(1);
                    //List<String> params = Splitter.on("&").splitToList(param);

                    if (!url.contains("characterencoding=utf-8") && !url.contains("characterencoding=utf8")) {
                        String errMsg = "The driver type is mysql, please configure the character encoding.";
                        System.err.println("\t\n*************************************************");
                        System.err.println("\t\n" + errMsg);
                        System.err.println("\t\n*************************************************");
                        throw new ApplicationContextException("The driver type is mysql, please configure the character encoding.");
                    }
                }
            }
        });

        app.run(args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(EngineServiceApplication.class);
    }

}